package com.lzs.common.interceptor;


import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

public class ReadTwiceFilter implements Filter {

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if(Objects.isNull(request)){
            chain.doFilter(request, response);
            return;
        }
        //上传文件请求直接放过
        if(((HttpServletRequest) request).getMethod().equals(HttpMethod.POST.name())
            && StringUtils.indexOf(request.getContentType(),"multipart/form-data")==0
        ){
            chain.doFilter(request, response);
        }else {
            ReadTwiceHttpServletRequestWrapper readTwiceHttpServletRequestWrapper = new ReadTwiceHttpServletRequestWrapper(
                    (HttpServletRequest) request);
            chain.doFilter(readTwiceHttpServletRequestWrapper, response);
        }



    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }
}
